package pkg.andru.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * some file utils
 * 
 * @author idiottiger
 * @version 1.0
 */
public class FileUtils {

	static final int BUFFER_SIZE = 16384;

	/**
	 * delete the file, if the file is a folder, will delete all sub folder's
	 * files
	 * 
	 * @param path
	 * @return true or false to indentify delete success or not
	 */
	public static boolean deleteFile(String path) {
		File file = new File(path);
		deleteFile2(file);
		return !file.exists();
	}

	private static void deleteFile2(File file) {
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File f : files) {
					deleteFile2(f);
				}
			} else {
				file.delete();
			}
		}
	}

	/**
	 * copy file form srcpath to destpath
	 * 
	 * @param srcPath
	 * @param destPath
	 * @return copy right or not
	 */
	public static boolean copyFile(String srcPath, String destPath) {
		File srcFile = new File(srcPath);
		if (!srcFile.exists() || !srcFile.canRead()) {
			return false;
		}

		int index = destPath.lastIndexOf("/");
		if (index == -1) {
			return false;
		}
		if (index != 0) {
			String basePath = destPath.substring(0, index);
			File baseFile = new File(basePath);
			if (!baseFile.exists() && !baseFile.mkdirs()) {
				return false;
			}
		}
		File destFile = new File(destPath);
		if (!destFile.canWrite()) {
			return false;
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(srcFile), BUFFER_SIZE);
			bos = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE);

			byte[] bytes = new byte[8192];
			int size = 0;
			while ((size = bis.read(bytes)) != -1) {
				bos.write(bytes, 0, size);
			}
			bos.flush();
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}
}
